<template>
	<view class="content">
		<u--form labelPosition="left" labelWidth="65%" :model="model" :rules="rules" errorType="toast" ref="uForm">
			<u-form-item class="item" :flexAble="false" className="img-formItem">
				<view class="item-left">头像</view>
				<view class="item-right">
					<view class="right-pic">
						<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
							<image class="right-pic avatarUrl" :src="model.avatarUrl" />
						</button>
					</view>
					<view class="rightIcon">
						<u-icon class="rightIcon" slot="right" name="arrow-right" color="#c0c4cc" size="16"></u-icon>
					</view>
				</view>
			</u-form-item>
			<u-form-item class="item" prop="nickName">
				<view class="item-left">昵称</view>
				<view class="item-right">
					<u-input type="nickname" disabledColor="#fff" v-model="model.nickName" placeholder="获取昵称"
						@blur="onNicknameInput" border="none" input-align="right" />
					<view class="rightIcon">
						<u-icon class="rightIcon" slot="right" name="arrow-right" color="#c0c4cc" size="16"></u-icon>
					</view>
				</view>
			</u-form-item>
			<u-form-item class="item" @click="showSex = true;" :flexAble="false" prop="sex">
				<view class="item-left">性别</view>
				<view class="item-right">
					<u--input class="right-pic" v-model="model.sex" disabled disabledColor="#ffffff" placeholder="请选择性别"
						border="none" input-align="right"></u--input>
					<view class="rightIcon">
						<u-icon class="rightIcon" slot="right" name="arrow-right" color="#c0c4cc" size="16"></u-icon>
					</view>
				</view>
			</u-form-item>
			<u-form-item class="item" prop="age">
				<view class="item-left">年龄</view>
				<view class="item-right">
					<u--input type="number" style="pointer-events: none;" disabledColor="#fff" v-model="model.age"
						border="none" input-align="right" placeholder="请填写年龄"></u--input>
					<view class="rightIcon">
						<u-icon class="rightIcon" slot="right" name="arrow-right" color="#c0c4cc" size="16"></u-icon>
					</view>
				</view>
			</u-form-item>
			<u-form-item class="item" prop="phone">
				<view class="item-left">手机号</view>
				<view class="item-right">
					<!-- <view class="phone-box" v-if="isBinded ==0"> -->
					<view class="phone-box" v-if="user_id">
						<view class="phone-btn">
							<u-button class="phoneBtn" size="mini" open-type="getPhoneNumber"
								@getphonenumber="onGetPhoneNumber">一键绑定</u-button>
						</view>
						<view class="rightIcon">
							<u-icon slot="right" name="arrow-right" color="#c0c4cc" size="16"></u-icon>
						</view>
					</view>
					<view class="phone-box" v-else>
						<view class="phone-txt">{{maskPhoneNumber(model.phone)}}</view>
						<view class="rightIcon">
							<u-button class="phoneBtn" size="mini" shape="circle" open-type="getPhoneNumber"
								@getphonenumber="onGetPhoneNumber">更换</u-button>
						</view>
					</view>
				</view>
			</u-form-item>
			<u-form-item class="item" :flexAble="false" className="img-formItem">
				<view class="item-left">我的二维码</view>
				<view class="item-right">
					<canvas canvas-id="qrcode" style="width: 60rpx;height:60rpx;" />
					<view class="rightIcon">
						<u-icon slot="right" name="arrow-right" color="#c0c4cc" size="16"></u-icon>
					</view>
				</view>
			</u-form-item>
			<u-form-item class="item" @click="handleImg" :flexAble="false" className="img-formItem">
				<view class="item-left">上传人脸照片</view>
				<view class="item-right">
					<image class="right-pic" :src="model.myPic" />
					<view class="rightIcon">
						<u-icon slot="right" name="arrow-right" color="#c0c4cc" size="16"></u-icon>
					</view>
				</view>
			</u-form-item>
			<view class="sub">
				<button @click="handleSave">保存</button>
			</view>
		</u--form>
		<u-action-sheet :show="showSex" :actions="actions" title="请选择性别" @close="showSex = false" @select="sexSelect">
		</u-action-sheet>
	</view>
</template>

<script>
	import {
		request,
		requestData
	} from '@/utils/http.js';
	export default {
		data() {
			return {
				user_id: null,
				model: {
					id: '',
					sex: '',
					nickName: '',
					phone: '',
					age: '',
					avatarUrl: '',
					myPic: '',
					myCodePic: '',
				},
				rules: {
					'nickName': {
						type: 'string',
						required: true,
						message: '请填写姓名/昵称',
						trigger: ['blur', 'change']
					},
					'age': {
						type: 'number',
						required: true,
						asyncValidator: (rule, value, callback) => {
							if (!value) {
								callback(new Error('请填写年龄'))
							} else if (isNaN(Number(value))) {
								callback(new Error('年龄必须是数字类型，请重新填写'))
							} else {
								callback()
							}
						},
						trigger: ['blur', 'change']
					},
				},
				actions: [{
						name: '男',
						value: 1,
					},
					{
						name: '女',
						value: 2
					},
				],
				showSex: false
			}
		},
		onLoad() {},
		onShow() {
			this.initData()
			this.makeQrcode()
		},
		onReady() {},
		methods: {
			initData() {
				this.initUesrInfo()
				this.$refs.uForm.setRules(this.rules);
				this.model.avatarUrl = uni.getStorageSync('avatarUrl') || require('@/static/img/default-avatar.png');
				this.model.nickName = uni.getStorageSync('nickName') || '昵称';
				this.model.phone = uni.getStorageSync('mobile') || '';
				this.model.myPic = uni.getStorageSync('myPic') || require('@/static/img/my-pic-default.png');
				this.model.myCodePic = uni.getStorageSync('myCodePic') || require('@/static/img/my-qrcode-default.png');
			},

			//手机号替换中间4位为星号
			maskPhoneNumber(phoneNumber) {
				if (phoneNumber.length === 11) {
					return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
				} else {
					return "手机号格式不正确";
				}
			},

			//初始info
			initUesrInfo() {
				request('/user/info/get', {}).then(res => {
					let sex = res?.datas?.gender
					let sexLabel = ''
					if (sex == 1) {
						sexLabel = '男'
					} else if (sex == 2) {
						sexLabel = '女'
					}
					this.model = {
						...this.model,
						...{
							id: res?.datas?.user_id || '',
							nickName: res?.datas?.nick_name || uni.getStorageSync('nickName'),
							sex: sexLabel,
							age: res?.datas?.age || '',
							phone: res?.datas?.mobile || '',
							avatarUrl: uni.getStorageSync('avatarUrl') ? uni.getStorageSync('avatarUrl') :
								require(
									'@/static/img/default-avatar.png'),
							myPic: uni.getStorageSync('myPic') || require('@/static/img/my-pic-default.png'),
							myCodePic: uni.getStorageSync('myCodePic') || require(
								'@/static/img/my-qrcode-default.png'),
						}
					}
					//这两项不从接口取，从缓存取
					// uni.setStorageSync('nickName', res?.datas?.nick_name || '昵称');
					// uni.setStorageSync('avatarUrl', res?.datas?.avatarUrl || '');

				}).catch(err => {
					console.log(err)
				})
			},

			// 表单提交
			handleSave() {
				let user_id = uni.getStorageSync('user_id')
				if (!user_id) {
					uni.showToast({
						title: '请先绑定手机号',
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/loginPhone/loginPhone',
						})
					}, 1000)
				} else {
					this.$refs.uForm.validate().then(res => {
						let sexLabel = this.model.sex;
						let gender = ''
						if (sexLabel == '男') {
							gender = 1
						} else if (sexLabel == '女') {
							gender = 2
						} else if (sex == '未知') {
							gender = 0
						}

						request('/user/info/update', {
							gender,
							age: Number(this.model.age),
							nick_name: this.model.nickName
						}).then(res => {
							if (res.code == 0) {
								uni.$u.toast('保存成功')
							} else {
								uni.$u.toast('保存失败')
							}
						}).catch(err => {
							console.log(err)
						})
					}).catch(errors => {
						//uni.$u.toast('校验失败')
					})
				}
			},

			//上传fn
			uploadHealth(str) {
				request("/user/facephoto/base64image/upload", {
					"user_id": uni.getStorageSync('user_id'),
					"image_base64": str,
					"image_ext": 'jpeg'
				}).then(res => {
					healthPic.value = res?.datas?.url
					uni.showToast({
						title: '上传成功！',
						icon: 'success',
					});
				}).catch(err => {
					console.log(err)
				})
			},

			//图片上传
			handleImg() {
				let that = this
				uni.chooseMedia({
					count: 1,
					mediaType: ['image'],
					sourceType: ['album', 'camera'],
					maxDuration: 30,
					camera: 'back',
					success(res) {
						if (res.tempFiles.length > 0) {
							const tempFilePath = res.tempFiles[0].tempFilePath;
							uni.getFileSystemManager().readFile({
								filePath: tempFilePath,
								encoding: 'base64',
								success: (data) => {
									uni.showToast({
										title: JSON.stringify(data),
										duration: 200000
									});
									let str = data.data;
									that.uploadHealth(str) //上传fn
								},
								fail: (err) => {
									uni.showToast({
										title: JSON.stringify(err),
										duration: 200000
									});
									console.error('读取文件失败:', err);
								}
							});
						}
					}
				})
			},

			//选择性别
			sexSelect(e) {
				this.model.sex = e.name
				this.$refs.uForm.validateField('sex')
			},

			//手机号
			onGetPhoneNumber(e) {
				const {
					detail: {
						encryptedData,
						iv,
						code
					}
				} = e;
				//console.log(e);
				if (e.detail.errMsg === "getPhoneNumber:ok") {
					let open_id = uni.getStorageSync('open_id');
					let access_token = uni.getStorageSync('access_token');
					request("/wxaccess/mp/user/getPhoneNumber", {
						"wxphone_code": code,
						'open_id': open_id
					}).then(res => {
						console.log(res)
						uni.setStorageSync('open_id', res?.datas?.open_id || '');
						uni.setStorageSync('user_id', res?.datas?.user_id || '');
						uni.setStorageSync('access_token', res?.datas?.access_token || '');
						//uni.setStorageSync('mobile_binded', res?.datas?.mobile_binded || 0);
						uni.setStorageSync('mobile', res?.datas.mobile || '');
						//this.isBinded = res?.datas?.mobile_binded;
					}).catch(err => {
						uni.showToast({
							title: err,
							duration: 2000,
							icon: "none"
						});
					})
				} else {
					uni.showToast({
						title: '为了给您提供更好的服务，请同意获取手机号！',
						duration: 2000,
						icon: "none"
					});
				}
			},

			//头像
			onChooseAvatar(e) {
				//console.log(e);
				const {
					avatarUrl
				} = e.detail
				this.model.avatarUrl = avatarUrl;
				uni.setStorageSync('avatarUrl', avatarUrl || '');
			},

			//昵称
			onNicknameInput(val) {
				console.log(111)
				console.log(val)
				console.log(this.model.nickName)
				this.model.nickName = val;
				uni.setStorageSync('nickName', val || '');
			},



		}
	}
</script>

<style lang="scss" scoped>
	/* 更改form样式
	https://gitcode.csdn.net/65ec454d1a836825ed795f5b.html?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NTIxMDQ4LCJleHAiOjE3MjQwNTQxMzUsImlhdCI6MTcyMzQ0OTMzNSwidXNlcm5hbWUiOiJxcV8zMzMzMjE4NCJ9.oGTHEemmtk-LQyb8Q8wT6vnYMGpHcw0g2D1P3RXuFXE
	 */
	* {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: #f7f7f8;
		// background: #f8f8f8;
	}

	.vue-ref {
		width: 100%;
	}

	.u-form {
		width: 100%;
		height: auto;
		padding: 0 20rpx;
		box-sizing: border-box;
	}

	::v-deep .u-form-item {
		width: 100% !important;
		height: 100% !important;
		box-sizing: border-box !important;
		font-size: 32rpx !important;
		// background: red !important;
	}

	::v-deep .u-form .u-form-item__body__right {
		flex-direction: row !important;
	}

	::v-deep .u-form-item__body__right__content__slot {
		flex-direction: row !important;
		width: 100%;
	}

	::v-deep .u-form-item__body__right_no_flex {
		width: 100% !important;
		height: 100% !important;
	}

	::v-deep .u-form-item__body {
		padding: 0 !important;
		height: 100% !important;
	}

	.item {
		width: 100%;
		padding: 0 20rpx;
		box-sizing: border-box;
		height: 100rpx;
		background: #fff;
		border-bottom: 1px solid #f5f5f0;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.item-left {
			width: 30%;
			display: flex;
			align-items: center;
			padding-left: 20rpx;
			// font-size: 28rpx;
		}

		.item-right {
			flex: 1;
			display: flex;
			justify-content: flex-end;
			align-items: center;
			font-size: 14rpx;
		}
	}

	.right-txt {}

	.rightIcon {
		margin-left: 20rpx;
	}

	.right-pic {
		width: 60rpx;
		height: 60rpx;
	}

	.avatarUrl {
		border-radius: 50%;
	}

	.avatar-wrapper {
		padding: 0;
		width: 60rpx;
		height: 60rpx;
		border-radius: 8rpx;
	}

	.avatar {
		display: block;
		width: 100%;
		height: 100%;
	}

	.container {
		display: flex;
	}


	.u-form-item__body__right__message {
		margin-left: 0;
	}

	::v-deep .u-button--info {
		background: $global-color-golden !important;
		width: 130rpx !important;
		z-index: 999;
		color: #fff !important;
		// border-radius: 20rpx !important;
	}

	.phone-box {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}

	.sub {
		width: 100%;
		height: auto;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 60rpx;
	}

	.sub button {
		border: none;
		width: 90%;
		height: 70rpx;
		line-height: 70rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: $global-color-golden;
		border-radius: 35rpx;
		color: #fff;
		font-weight: 400;
	}

	// .item-right-data {
	// 	padding-right: 50rpx;
	// }

	.phone-txt {
		font-size: 28rpx;
	}

	::v-deep .u-form-item__body__right__message {
		margin-left: 20rpx !important;
	}
</style>